<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <TodoHeader :todos="todos"/>
      <TodoList :todos="todos"/>
      <TodoFooter ref="todoFooter" :todos="todos" :removeCompleteTodos="removeCompleteTodos" :seleteAllTodos="seleteAllTodos"/>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import TodoHeader from './TodoHeader'
import TodoList from './TodoList'
import TodoFooter from './TodoFooter'
import Storage from '../../util/StorageUtil.js'
export default {
  name: 'TodosMain',
  data () {
    return {
      todos: Storage.readTodos(),
      loading: Storage.loading
    }
  },
  mounted () {
    this.$refs.todoFooter.$on('removeCompleteTodos', this.removeCompleteTodos)
    PubSub.subscribe('deteleTodo', (msg, index) => {
      this.deteleTodo(index)
    })
  },
  methods: {
    deteleTodo (index) {
      this.todos.splice(index, 1)
    },
    removeCompleteTodos () {
      this.todos = this.todos.filter(todo => !todo.complete)
    },
    seleteAllTodos (check) {
      this.todos.forEach(todo => (todo.complete = check))
    }
  },
  watch: {
    todos: {
      deep: true,
      handler: Storage.saveTodos
    }
  },
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  }
}
</script>

<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    text-align: left;
  }
</style>
